<template>
  <Dialog v-model="dialogVisible" title="生成督导报告" width="700px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="报告类型" prop="reportType">
        <el-radio-group v-model="formData.reportType">
          <el-radio label="单次检查">单次检查报告</el-radio>
          <el-radio label="阶段汇总">阶段汇总报告</el-radio>
          <el-radio label="年度总结">年度总结报告</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="报告名称" prop="reportName">
        <el-input v-model="formData.reportName" placeholder="请输入报告名称" />
      </el-form-item>
      
      <el-form-item label="时间范围" prop="timeRange" v-if="formData.reportType !== '单次检查'">
        <el-date-picker
          v-model="formData.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="检查记录" v-if="formData.reportType === '单次检查'">
        <el-select
          v-model="formData.supervisionId"
          placeholder="请选择检查记录"
          style="width: 100%"
        >
          <el-option
            v-for="record in supervisionList"
            :key="record.id"
            :label="`${record.checkTime} - ${record.checkContent}`"
            :value="record.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="包含内容">
        <el-checkbox-group v-model="formData.includeContent">
          <el-checkbox label="检查概况">检查概况</el-checkbox>
          <el-checkbox label="发现问题">发现问题</el-checkbox>
          <el-checkbox label="整改建议">整改建议</el-checkbox>
          <el-checkbox label="统计分析">统计分析</el-checkbox>
          <el-checkbox label="趋势分析">趋势分析</el-checkbox>
          <el-checkbox label="附件材料">附件材料</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="报告格式" prop="reportFormat">
        <el-radio-group v-model="formData.reportFormat">
          <el-radio label="PDF">PDF格式</el-radio>
          <el-radio label="Word">Word格式</el-radio>
          <el-radio label="Excel">Excel格式</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="报告模板">
        <el-select
          v-model="formData.templateId"
          placeholder="请选择报告模板"
          style="width: 100%"
        >
          <el-option label="标准模板" value="standard" />
          <el-option label="详细模板" value="detailed" />
          <el-option label="简化模板" value="simple" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="其他说明">
        <el-input
          v-model="formData.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入其他说明"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="generateReport" type="primary" :disabled="formLoading">
        生成报告
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'ReportGenerate' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const supervisionList = ref([])

const formData = reactive({
  reportType: '单次检查',
  reportName: '',
  timeRange: null,
  supervisionId: undefined,
  includeContent: ['检查概况', '发现问题', '整改建议'],
  reportFormat: 'PDF',
  templateId: 'standard',
  remarks: ''
})

const formRules = reactive({
  reportType: [{ required: true, message: '请选择报告类型', trigger: 'change' }],
  reportName: [{ required: true, message: '请输入报告名称', trigger: 'blur' }],
  timeRange: [{ required: true, message: '请选择时间范围', trigger: 'change' }],
  reportFormat: [{ required: true, message: '请选择报告格式', trigger: 'change' }]
})

// 监听报告类型变化，自动设置报告名称
watch(() => formData.reportType, (newType) => {
  const now = new Date()
  const dateStr = now.toISOString().split('T')[0]
  
  switch (newType) {
    case '单次检查':
      formData.reportName = `督导检查报告_${dateStr}`
      break
    case '阶段汇总':
      formData.reportName = `督导检查阶段汇总报告_${dateStr}`
      break
    case '年度总结':
      formData.reportName = `督导检查年度总结报告_${now.getFullYear()}`
      break
  }
})

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  await loadSupervisionList()
  resetForm()
}

/** 加载督导检查记录列表 */
const loadSupervisionList = async () => {
  try {
    // TODO: 调用获取督导检查记录列表的API
    supervisionList.value = []
  } catch (error) {
    console.error('加载督导检查记录失败:', error)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.reportType = '单次检查'
  formData.reportName = `督导检查报告_${new Date().toISOString().split('T')[0]}`
  formData.timeRange = null
  formData.supervisionId = undefined
  formData.includeContent = ['检查概况', '发现问题', '整改建议']
  formData.reportFormat = 'PDF'
  formData.templateId = 'standard'
  formData.remarks = ''
  formRef.value?.resetFields()
}

/** 生成报告 */
const generateReport = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  // 验证必填项
  if (formData.reportType !== '单次检查' && !formData.timeRange) {
    ElMessage.error('请选择时间范围')
    return
  }
  
  if (formData.reportType === '单次检查' && !formData.supervisionId) {
    ElMessage.error('请选择检查记录')
    return
  }
  
  if (formData.includeContent.length === 0) {
    ElMessage.error('请至少选择一项包含内容')
    return
  }
  
  try {
    formLoading.value = true
    
    const reportData = {
      reportType: formData.reportType,
      reportName: formData.reportName,
      timeRange: formData.timeRange,
      supervisionId: formData.supervisionId,
      includeContent: formData.includeContent,
      reportFormat: formData.reportFormat,
      templateId: formData.templateId,
      remarks: formData.remarks
    }
    
    // TODO: 调用生成报告的API
    // const result = await generateSupervisionReport(reportData)
    
    ElMessage.success('报告生成成功，请稍后下载')
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('生成报告失败:', error)
    ElMessage.error('生成报告失败')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped>
.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}

.el-checkbox {
  margin-right: 20px;
  margin-bottom: 10px;
}
</style>
